import requests
from lxml import etree
import os

def spider_pic(pic_url):
    url2 = []
    url3 = []
    try:
        response = requests.get(pic_url)
        response.encoding = "utf-8"
        selector = etree.HTML(response.text)
        page_pic = selector.xpath('//figure/a/@href')
        print(page_pic)
        for j in page_pic:
            response2 = requests.get(j)
            response2.encoding = "utf-8"
            selector = etree.HTML(response2.text)
            page_pic2 = selector.xpath('//img[@id="wallpaper"]/@src')
            url3.append(page_pic2[0])
        print(url3)
        for k in url3:
            pic_url2 = "https:" + "{}".format(k)
            url2.append(pic_url2)
        print(url2[:])
                # print(pic_url2)
        for n in url2:
            try:
                with open('e:\\python\\second\\picture\\page{}\\this_page{}_list.txt'.format(i, i), 'a+') as e:
                    e.write("{}\n".format(n))
            except:
                print("文件加载失败")
        b = 0

        try:
            for m in url2:
                b = b + 1
                print(m)
                response3 = requests.get(m)
                with open("e:\\python\\second\\picture\\page{}\\This_is_page_{}picture{}.png".format(i, i, b), "wb+") as e:
                    e.write(response3.content)

        except:
                    print("下载失败")
    except:
        print("连接失败")

for i in range(7, 20):
    url = "https://alpha.wallhaven.cc/search?q=&categories=001&purity=100&topRange=1M&sorting=toplist&order=desc&page={}".format(i)
    try:
        os.mkdir("page{}".format(i))
        spider_pic(url)
    except:
        print("当文件已存在时，无法创建该文件")


